﻿using DevExpress.Web.ASPxTreeView;
using DevExpress.XtraReports.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using EntryExit.Utils;
using System.Web.UI;

namespace EntryExit
{
    public partial class Reports : BasePage
    {
        public int SerialCounter { get; set; }
        public XtraReport CurrentReport
        {
            get
            {
                return (XtraReport)Session[SessionKeys.REPORT_DATA];
            }
            set
            {
                Session[SessionKeys.REPORT_DATA] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (Session["Searched"] == "1")
                {
                    reportViewer.Report = null;
                    reportViewer.Width = System.Web.UI.WebControls.Unit.Percentage(100);
                    reportViewer.Height = System.Web.UI.WebControls.Unit.Percentage(100);
                    CurrentReport = null;
                }

                if (CurrentReport != null)
                {
                    reportViewer.Report = CurrentReport;
                }

                Session["Searched"] = "0";
            }
            else
            {
                calendarStart.MaxDate = DateTime.Now.Date;
                calendarEnd.MaxDate = DateTime.Now.Date;
                if (this.Master is MainMaster)
                {
                    ((MainMaster)this.Master).SetAllowCheckingInTreeview();
                    ((MainMaster)this.Master).DisableGroupedChecking();
                    ViewState[SessionKeys.GROUPED_CHECK_PREFERANCE_STATE] = false;
                }
                DefaultCalendarValues();
            }

        }

        private void DefaultCalendarValues()
        {
            DateTime today = DateTime.Now;
            int date = DateTime.DaysInMonth(today.Month == 1 ? today.Year - 1 : today.Year, today.Month == 1 ? 12 : today.Month - 1) >= DateTime.Today.Day ? DateTime.Today.Day : DateTime.DaysInMonth(today.Month == 1 ? today.Year - 1 : today.Year, today.Month == 1 ? 12 : today.Month - 1);
            calendarStart.Date = new DateTime(today.Month == 1 ? today.Year - 1 : today.Year, today.Month == 1 ? 12 : today.Month - 1, date);
            calendarEnd.Date = new DateTime(today.Year, today.Month, DateTime.Today.Day);
        }

        protected void reportViewer_Unload(object sender, EventArgs e)
        {
            reportViewer.Report = null;
        }

        protected void btnGenReport_Click(object sender, EventArgs e)
        {

            try
            {  
                UpdateSelectedEmployees();


                lblError.Visible = false;
                bool needHardLoading = false;
                DateTime startDate = calendarStart.Date;
                DateTime endDate = calendarEnd.Date;
                if (endDate < startDate)
                {
                    lblError.Visible = true;
                    lblError.Text = "Error : Selected end date is less than start date";
                
                    // By Rajkumar on 24.02.2014
                    // To clear reportviewer data. The last report data will persists in viewer unless we clear.
                    reportViewer.Report = null;

                    return;
                }
                if (SelectedEmployees.Count == 0)
                {
                    lblError.Visible = true;
                    lblError.Text = "Error : No employees are selected for the report";

                    // By Rajkumar on 24.02.2014
                    // To clear reportviewer data. The last report data will persists in viewer unless we clear.
                    reportViewer.Report = null;

                    return;
                }
                
                reportViewer.Report = null;

                if (CurrentReport == null)
                {
                    needHardLoading = true;
                }
                switch (ddlReportType.SelectedIndex)
                {
                    case 0:
                        CurrentReport = GetReportForLowWorkHours(startDate, endDate);
                        break;
                    case 1:
                        CurrentReport = GetReportForOverWorkHours(startDate, endDate);
                        break;
                    case 2:
                        CurrentReport = GetReportForLateBy(startDate, endDate);
                        break;
                    case 3:
                        CurrentReport = GetReportForEarlyOut(startDate, endDate);
                        break;
                    case 4:
                        CurrentReport = GetReportForAttendance(startDate, endDate);
                        break;
                    case 5:
                        CurrentReport = GetLeaveReport(startDate, endDate);
                        break;
                    case 6:
                        CurrentReport = GetAbscondingReport(startDate, endDate);
                        break;
                    case 7:
                        CurrentReport = GetReportForDetailedReport(startDate, endDate);

                        break;
                    case 8:
                        CurrentReport = GetInsiderReport();
                        break;
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                    case 13:

                        CurrentReport = GetReportForLowWorkHoursReport(startDate, endDate, ddlReportType.SelectedIndex);
                        break;

                    default:
                        CurrentReport = null;
                        break;
                }
                if (needHardLoading)
                {
                    reportViewer.Report = CurrentReport;

                    this.Page_Load(null, null);
                }
                reportViewer.Report = CurrentReport;
            
            }
            catch (Exception ex)
            {
                Logger.Error("Page : Reports.aspx.cs, Event : btnGenReport_Click",ex);
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('An internal error occured. Reload the tool and try again. If issue still persists, please report to your administrator..!');", true);
            }
        }

        private void UpdateSelectedEmployees()
        {
            SelectedEmployees.Clear();
            List<Employee> employees = new List<Employee>();
            if (this.Master is MainMaster)
            {
                employees = ((MainMaster)this.Master).GetAllSelectedEmployees();
            }
            SelectedEmployees = employees;

        }
        protected void btnGroupSelection_Click(object sender, EventArgs e)
        {
            if (this.Master is MainMaster)
            {
                if ((bool)ViewState[SessionKeys.GROUPED_CHECK_PREFERANCE_STATE])
                {
                    ViewState[SessionKeys.GROUPED_CHECK_PREFERANCE_STATE] = false;
                    ((MainMaster)this.Master).DisableGroupedChecking();
                    btnGroupedSelection.Text = "Enable Grouped Selection";
                }
                else
                {
                    ViewState[SessionKeys.GROUPED_CHECK_PREFERANCE_STATE] = true;
                    ((MainMaster)this.Master).EnableGroupedChecking();
                    btnGroupedSelection.Text = "Disable Grouped Selection";
                }
            }
        }
        private XtraReport GetInsiderReport()
        {
            SerialCounter = 1;
            DataTable insiderData = new DataTable();
            insiderData.Columns.Add("SlNo");
            insiderData.Columns.Add("Name");
            insiderData.Columns.Add("Gate");
            insiderData.Columns.Add("Date");
            insiderData.Columns.Add("AuthorityName");

            string reportHeadPart = " employees inside EY as of " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();

            DateTime startDate = DateTime.Now.Date.AddDays(-1).AddHours(00).AddMinutes(00).AddSeconds(00);//..ToShortDateString() + " 00:00:00";
            DateTime endDate = DateTime.Now.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    LocationStatus locStatus = EmployeeManagerContext.GetLatestLocationStatus(startDate, endDate, emp.CardHolderId);
                    if (locStatus != null)
                    {
                        if (locStatus.Action == "ENTRY")
                        {
                            insiderData.Rows.Add(SerialCounter, emp.EmployeeName, locStatus.ActionGate,
                                locStatus.LastStatusDateTime.ToShortDateString() + " " + locStatus.LastStatusDateTime.ToShortTimeString(), emp.AuthorityName);
                            SerialCounter++;
                        }
                    }
                }
            }
            reportHeadPart = insiderData.Rows.Count + reportHeadPart;

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(insiderData);

            XtraReport rpt = new InsiderReports(reportHeadPart, dtsorted);
            rpt.Name = "InsiderReport";
            return rpt;
        }

        private XtraReport GetAbscondingReport(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Unauthorised absentees among selected employees during " +
                startDate.ToString("dd/MM/yyyy") + " to " +
                endDate.ToString("dd/MM/yyyy");
            DataTable absconderData = new DataTable();
            absconderData.Columns.Add("SlNo");
            absconderData.Columns.Add("LPN");
            absconderData.Columns.Add("Name");
            absconderData.Columns.Add("Date");
            absconderData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                Dictionary<string, AttendanceInfo> attendance;
                foreach (Employee emp in SelectedEmployees)
                {
                    attendance = null;
                    attendance = EmployeeManagerContext.GetEmployeeAttendanceWithLeave(startDate, endDate, emp.CardHolderId, emp.LPN);

                    if (attendance != null)
                    {
                        foreach (KeyValuePair<string, AttendanceInfo> kvPair in attendance)
                        {
                            if (kvPair.Value.StatusId == UIConstants.IDENTIFIER_NO_ATTENDANCE_DATA_NO_LEAVE_DATA)
                            {
                                DateTime checkingDate = DateTime.Parse(kvPair.Key);
                                if (checkingDate < DateTime.Now && checkingDate > emp.JoiningDate)
                                {
                                    absconderData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName, checkingDate.ToString("dd/MM/yyyy"), emp.AuthorityName);
                                    SerialCounter++;
                                }
                            }
                        }
                    }
                }
            }

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(absconderData);


            XtraReport rpt = new UnAuthAbsenteeReport(reportHeadPart, dtsorted);
            rpt.Name = "UnauthorisedAbsenceReport";
            return rpt;
        }

        private XtraReport GetLeaveReport(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Leave report of selected employees during " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable leaveInfo = new DataTable();
            leaveInfo.Columns.Add("SlNo");
            leaveInfo.Columns.Add("LPN");
            leaveInfo.Columns.Add("Name");
            leaveInfo.Columns.Add("Date");
            leaveInfo.Columns.Add("Leave");
            leaveInfo.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                EmployeeManager localEmpMgrContext = EmployeeManagerContext;
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, int> leaveData = localEmpMgrContext.GetLeavesMarked(startDate, endDate, emp.LPN);

                    if (leaveData != null)
                    {
                        foreach (KeyValuePair<string, int> kvPair in leaveData)
                        {
                            LeaveLegend leaveId = (LeaveLegend)kvPair.Value;
                            if (leaveId != LeaveLegend.Working)
                            {
                                string loopLeaveType = localEmpMgrContext.GetLeaveInfo(leaveId);
                                if (!String.IsNullOrEmpty(loopLeaveType))
                                {
                                    leaveInfo.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                        Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), loopLeaveType, emp.AuthorityName);
                                    SerialCounter++;
                                }
                            }
                        }
                    }
                }
            }

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(leaveInfo);


            XtraReport rpt = new LeaveReport(reportHeadPart, dtsorted);
            rpt.Name = "LeaveReport";
            return rpt;
        }

        private XtraReport GetReportForLowWorkHours(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Selected employees with low work hours during : "
                + startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable lowWorkHoursData = new DataTable();
            lowWorkHoursData.Columns.Add("SlNo");
            lowWorkHoursData.Columns.Add("LPN");
            lowWorkHoursData.Columns.Add("Name");
            lowWorkHoursData.Columns.Add("Date");
            lowWorkHoursData.Columns.Add("Hours");
            lowWorkHoursData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, AttendanceInfo> attendance = EmployeeManagerContext.GetEmployeeAttendanceWithLeave(startDate,
                        endDate, emp.CardHolderId, emp.LPN);

                    if (attendance != null)
                    {
                        foreach (KeyValuePair<string, AttendanceInfo> kvPair in attendance)
                        {
                            AttendanceInfo info = kvPair.Value;
                            if (info.StatusId == UIConstants.IDENTIFIER_LOW_WORK_HOURS || info.StatusId == UIConstants.IDENTIFIER_LESSTHAN3_WORK_HOURS)
                            {
                                lowWorkHoursData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                    Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), Convert.ToString(info.TotalInTime), emp.AuthorityName);
                                SerialCounter++;
                            }
                        }
                    }
                }
            }

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(lowWorkHoursData);


            XtraReport rpt = new WorkHourReport(reportHeadPart, dtsorted);
            rpt.Name = "LowWorkHoursReport";
            return rpt;
        }

        private DataTable sortSerial(DataTable dt)
        {
            DataTable dt2 = new DataTable();
           
            dt.DefaultView.Sort = "AuthorityName, Name";
            DataView dw = dt.DefaultView;

            for (int count = 0; count < dw.Count; count++)
            {
                dw[count]["SlNo"] = count + 1;
            }

           
            dt2 = dw.ToTable();

            return dt2;
        }

        private DataTable sortSerial2(DataTable dt)
        {
            DataTable dt2 = new DataTable();

            dt.DefaultView.Sort = "AuthorityName, EmployeeName";
            DataView dw = dt.DefaultView;

            for (int count = 0; count < dw.Count; count++)
            {
                dw[count]["SlNo"] = count + 1;
            }


            dt2 = dw.ToTable();

            return dt2;
        }

        private XtraReport GetReportForOverWorkHours(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeading = "Selected employees with over work hours during : " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable overWorkHoursData = new DataTable();
            overWorkHoursData.Columns.Add("SlNo");
            overWorkHoursData.Columns.Add("LPN");
            overWorkHoursData.Columns.Add("Name");
            overWorkHoursData.Columns.Add("Date");
            overWorkHoursData.Columns.Add("Hours");
            overWorkHoursData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, AttendanceInfo> attendance = EmployeeManagerContext.GetEmployeeAttendanceWithLeave(startDate,
                        endDate, emp.CardHolderId, emp.LPN);

                    if (attendance != null)
                    {
                        foreach (KeyValuePair<string, AttendanceInfo> kvPair in attendance)
                        {
                            AttendanceInfo info = kvPair.Value;
                            if (info.StatusId == UIConstants.IDENTIFIER_OVER_WORK_HOURS)
                            {
                                overWorkHoursData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                    Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), Convert.ToString(info.TotalInTime), emp.AuthorityName);
                                SerialCounter++;
                            }
                        }
                    }
                }
            }

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(overWorkHoursData);


            XtraReport rpt = new WorkHourReport(reportHeading, dtsorted);
            rpt.Name = "OverWorkHoursReport";
            return rpt;
        }

        private XtraReport GetReportForLowWorkHoursReport(DateTime startDate, DateTime endDate, int index)
        {

            string reportHeadPart = string.Empty;
            string selectedLPNs = "";
            System.Type tp = System.Type.GetType("System.Date");
            DataTable LowworkingEmployees = new DataTable();
            DataColumn bindingSlNo = new DataColumn("SlNo");
            DataColumn bindingLPN = new DataColumn("LPN");
            DataColumn bindingName = new DataColumn("Name");
            DataColumn bindingDate = new DataColumn("Date", typeof(String));
            DataColumn bindingHours = new DataColumn("Hours");
            DataColumn bindingAuthorityName = new DataColumn("AuthorityName");

            XtraReport rpt = new XtraReport();

            if (SelectedEmployees != null)
            {

                foreach (var item in SelectedEmployees)
                {
                    selectedLPNs += item.LPN + "|";
                }
                if (selectedLPNs.Length > 0)

                    selectedLPNs = selectedLPNs.Remove(selectedLPNs.Length - 1);
            }

            DataTable dtsorted = new DataTable();


            if (!string.IsNullOrEmpty(selectedLPNs) && selectedLPNs.Length > 0)
            {
                switch (index)
                {

                    case 9:
                        reportHeadPart = "Employees worked less than 4 hours during : " +
                 startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
                        LowworkingEmployees = EmployeeManagerContext.GetLowWorkingEmployees(startDate, endDate, selectedLPNs, ReportTypes.Lessthan4);

                        dtsorted = sortSerial2(LowworkingEmployees);

                        rpt = new LowWorkHours(dtsorted, reportHeadPart, false);
                        rpt.Name = "Lessthan4HoursReport";
                        break;
                    case 10:
                        reportHeadPart = "Employees worked less than 7 hours during : " +
                  startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
                        LowworkingEmployees = EmployeeManagerContext.GetLowWorkingEmployees(startDate, endDate, selectedLPNs, ReportTypes.Lessthan7);

                        dtsorted = sortSerial2(LowworkingEmployees);

                        rpt = new LowWorkHours(dtsorted, reportHeadPart, false);
                        rpt.Name = "Lessthan7HoursReport";
                        break;
                    case 11:
                        reportHeadPart = "Employees worked less than 8 hours during : " +
                  startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
                        LowworkingEmployees = EmployeeManagerContext.GetLowWorkingEmployees(startDate, endDate, selectedLPNs, ReportTypes.Lessthan8);

                        dtsorted = sortSerial2(LowworkingEmployees);

                        rpt = new LowWorkHours(dtsorted, reportHeadPart, false);
                        rpt.Name = "Lessthan8HoursReport";
                        break;

                    case 12:
                        reportHeadPart = "Employees worked less than 40 hours during : " +
                  startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
                        LowworkingEmployees = EmployeeManagerContext.GetLowWorkingEmployees(startDate, endDate, selectedLPNs, ReportTypes.Lessthan40);

                        dtsorted = sortSerial2(LowworkingEmployees);

                        rpt = new LowWorkHours(dtsorted, reportHeadPart, true);
                        rpt.Name = "Lessthan40HoursReport";
                        break;
                    case 13:
                        reportHeadPart = "Employees worked less than 160 hours during : " +
                  startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
                        LowworkingEmployees = EmployeeManagerContext.GetLowWorkingEmployees(startDate, endDate, selectedLPNs, ReportTypes.Lessthan160);

                        dtsorted = sortSerial2(LowworkingEmployees);

                        rpt = new LowWorkHours(dtsorted, reportHeadPart, true);
                        rpt.Name = "Lessthan160HoursReport";
                        break;

                }
            }


            //if (SelectedEmployees != null)
            //{
            //    foreach (Employee emp in SelectedEmployees)
            //    {
            //        Dictionary<string, AttendanceInfo> attendanceInfos = EmployeeManagerContext.
            //            GetEmployeeAttendanceWithLeave(startDate, endDate, emp.CardHolderId, emp.LPN);
            //        //To Do, capture swipe in and swipe out time when getting attendance
            //        Dictionary<string, DateTime> swipein = EmployeeManagerContext.GetEmployeeFirstSwipe(startDate, endDate, emp.CardHolderId);
            //        Dictionary<string, DateTime> swipeout = EmployeeManagerContext.GetEmployeeLastSwipe(startDate, endDate, emp.CardHolderId);
            //        if (attendanceInfos != null)
            //        {
            //            foreach (KeyValuePair<string, AttendanceInfo> kvPair in attendanceInfos)
            //            {
            //                if (swipein.ContainsKey(kvPair.Key) && swipeout.ContainsKey(kvPair.Key))
            //                {
            //                    detailedAttendanceData.Rows.Add(emp.EmployeeName, swipein[kvPair.Key].ToShortTimeString(),
            //                        swipeout[kvPair.Key].ToShortTimeString(),
            //                        Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), Convert.ToString(kvPair.Value.TotalInTime));
            //                }
            //            }
            //        }
            //    }
            //}


            return rpt;
        }

        private XtraReport GetReportForDetailedReport(DateTime startDate, DateTime endDate)
        {
            string reportHeadPart = "Detailed Attendance of selected employees during : " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable detailedAttendanceData = new DataTable();
            detailedAttendanceData.Columns.Add("Name");
            detailedAttendanceData.Columns.Add("SwipeIn");
            detailedAttendanceData.Columns.Add("SwipeOut");
            detailedAttendanceData.Columns.Add("Date");
            detailedAttendanceData.Columns.Add("TotalHours");
            detailedAttendanceData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, AttendanceInfo> attendanceInfos = EmployeeManagerContext.
                        GetEmployeeAttendanceWithLeave(startDate, endDate, emp.CardHolderId, emp.LPN);
                    //To Do, capture swipe in and swipe out time when getting attendance
                    //Dictionary<string, DateTime> swipein = EmployeeManagerContext.GetEmployeeFirstSwipe(startDate, endDate, emp.CardHolderId);
                    //Dictionary<string, DateTime> swipeout = EmployeeManagerContext.GetEmployeeLastSwipe(startDate, endDate, emp.CardHolderId);
                    DataTable dt = EmployeeManagerContext.GetEmployeeDetailReport(startDate, endDate, emp.CardHolderId);

                    foreach (DataRow dr1 in dt.Rows)
                    {
                        DataRow dr = detailedAttendanceData.NewRow();
                        dr.ItemArray = dr1.ItemArray;
                        detailedAttendanceData.Rows.Add(dr);
                    }
                    //if (attendanceInfos != null)
                    //{
                    //    foreach (KeyValuePair<string, AttendanceInfo> kvPair in attendanceInfos)
                    //    {
                    //        if (swipein.ContainsKey(kvPair.Key) && swipeout.ContainsKey(kvPair.Key))
                    //        {
                    //            detailedAttendanceData.Rows.Add(emp.EmployeeName, swipein[kvPair.Key].ToShortTimeString(),
                    //                swipeout[kvPair.Key].ToShortTimeString(),
                    //                Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), Convert.ToString(kvPair.Value.TotalInTime), emp.AuthorityName);
                    //        }
                    //    }
                    //}
                }
            }

            XtraReport rpt = new DetailedReports(reportHeadPart, detailedAttendanceData);
            rpt.Name = "DetailedReport";
            return rpt;
        }

        private XtraReport GetReportForAttendance(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Attendance of selected employees during : " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable attendanceData = new DataTable();
            attendanceData.Columns.Add("SlNo");
            attendanceData.Columns.Add("LPN");
            attendanceData.Columns.Add("Name");
            attendanceData.Columns.Add("Date");
            attendanceData.Columns.Add("LateBy");
            attendanceData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, TimeSpan> attendance = EmployeeManagerContext.
                        GetAttendance(startDate, endDate, emp.CardHolderId);
                    if (attendance != null)
                    {
                        foreach (KeyValuePair<string, TimeSpan> kvPair in attendance)
                        {
                            attendanceData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), kvPair.Value.ToString(), emp.AuthorityName);
                            SerialCounter++;
                        }
                    }
                }
            }

            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(attendanceData);


            XtraReport rpt = new AttendanceReports(reportHeadPart, dtsorted);
            rpt.Name = "AttendanceReport";
            return rpt;
        }

        private XtraReport GetReportForLateBy(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Selected employees with late entry during " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable lateInData = new DataTable();
            lateInData.Columns.Add("SlNo");
            lateInData.Columns.Add("LPN");
            lateInData.Columns.Add("Name");
            lateInData.Columns.Add("Date");
            lateInData.Columns.Add("LateBy");
            lateInData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, TimeSpan> attendance = EmployeeManagerContext.GetAttendance(startDate, endDate, emp.CardHolderId);
                    Dictionary<string, int> shiftData = EmployeeManagerContext.GetEmployeeShiftAllocation(startDate, endDate, emp.LPN);
                    Dictionary<string, DateTime> swipein = EmployeeManagerContext.GetFirstSwipe(startDate, endDate, emp.CardHolderId,true);
                    if (attendance != null && shiftData != null)
                    {
                        string loopLateValue = string.Empty;
                        foreach (KeyValuePair<string, TimeSpan> kvPair in attendance)
                        {
                            if (swipein.ContainsKey(kvPair.Key))
                            {
                                if (shiftData.ContainsKey(kvPair.Key))
                                {
                                    loopLateValue = CalculateLateIn(shiftData[kvPair.Key], swipein[kvPair.Key], swipein[kvPair.Key]);
                                    if (loopLateValue != "00:00")
                                    {
                                        lateInData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                            Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), loopLateValue, emp.AuthorityName);
                                        SerialCounter++;
                                    }
                                }
                                else
                                {
                                    loopLateValue = CalculateLateIn(4, swipein[kvPair.Key], swipein[kvPair.Key]);
                                    if (loopLateValue != "00:00")
                                    {
                                        lateInData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                            Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), loopLateValue, emp.AuthorityName);
                                        SerialCounter++;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(lateInData);


            XtraReport rpt = new LateInReports(reportHeadPart, dtsorted);
            rpt.Name = "LateInReport";
            return rpt;
        }

        public string CalculateLateIn(int shiftId, DateTime swipeIn, DateTime expectedInTime)
        {
            string lateby = string.Empty;
            switch (shiftId)
            {
                case 1:
                    expectedInTime = Convert.ToDateTime(string.Format("{0} {1}", expectedInTime.ToShortDateString(), "14:00:00"));
                    break;
                case 2:
                    expectedInTime = Convert.ToDateTime(string.Format("{0} {1}", expectedInTime.ToShortDateString(), "06:00:00"));
                    break;
                case 3:
                    expectedInTime = Convert.ToDateTime(string.Format("{0} {1}", expectedInTime.ToShortDateString(), "11:30:00"));
                    break;
                case 4:
                    expectedInTime = Convert.ToDateTime(string.Format("{0} {1}", expectedInTime.ToShortDateString(), "09:00:00"));
                    break;
                case 5:
                    expectedInTime = Convert.ToDateTime(string.Format("{0} {1}", expectedInTime.ToShortDateString(), "23:00:00"));
                    break;
            }
            if (swipeIn > expectedInTime)
            {
                lateby = Convert.ToString(swipeIn - expectedInTime);
            }
            else
            {
                lateby = "00:00";
            }
            return lateby;
        }

        private XtraReport GetReportForEarlyOut(DateTime startDate, DateTime endDate)
        {
            SerialCounter = 1;
            string reportHeadPart = "Selected employees with early out during " +
                startDate.ToString("dd/MM/yyyy") + " to " + endDate.ToString("dd/MM/yyyy");
            DataTable earlyOutData = new DataTable();
            earlyOutData.Columns.Add("SlNo");
            earlyOutData.Columns.Add("LPN");
            earlyOutData.Columns.Add("Name");
            earlyOutData.Columns.Add("Date");
            earlyOutData.Columns.Add("EarlyBy");
            earlyOutData.Columns.Add("AuthorityName");

            if (SelectedEmployees != null)
            {
                foreach (Employee emp in SelectedEmployees)
                {
                    Dictionary<string, TimeSpan> attendance = EmployeeManagerContext.GetAttendance(startDate, endDate, emp.CardHolderId);
                    Dictionary<string, int> shiftData = EmployeeManagerContext.GetEmployeeShiftAllocation(startDate, endDate, emp.LPN);
                    Dictionary<string, DateTime> swipeout = EmployeeManagerContext.GetFirstSwipe(startDate, endDate, emp.CardHolderId,false);
                    if (attendance != null && shiftData != null)
                    {
                        string loopEarlyValue = string.Empty;
                        foreach (KeyValuePair<string, TimeSpan> kvPair in attendance)
                        {
                            if (swipeout.ContainsKey(kvPair.Key))
                            {
                                if (shiftData.ContainsKey(kvPair.Key))
                                {
                                    loopEarlyValue = CalculateEarlyBy(shiftData[kvPair.Key], swipeout[kvPair.Key], swipeout[kvPair.Key], kvPair.Key);
                                    if (loopEarlyValue != "00:00")
                                    {
                                        earlyOutData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                            Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), loopEarlyValue, emp.AuthorityName);
                                        SerialCounter++;
                                    }
                                }
                                else
                                {
                                    loopEarlyValue = CalculateEarlyBy(4, swipeout[kvPair.Key], swipeout[kvPair.Key], kvPair.Key);
                                    if (loopEarlyValue != "00:00")
                                    {
                                        earlyOutData.Rows.Add(SerialCounter, emp.LPN, emp.EmployeeName,
                                            Convert.ToDateTime(kvPair.Key).ToString("dd/MM/yyyy"), loopEarlyValue, emp.AuthorityName);
                                        SerialCounter++;
                                    }

                                }
                            }

                        }
                    }
                }
            }


            DataTable dtsorted = new DataTable();
            dtsorted = sortSerial(earlyOutData);

            XtraReport rpt = new EarlyOutReports(reportHeadPart, dtsorted);
            rpt.Name = "EarlyOutReport";
            return rpt;
        }

        public string CalculateEarlyBy(int shiftId, DateTime swipeOut, DateTime expectedOutTime, string ShiftDate)
        {
            string earlyby = string.Empty;
            DateTime shiftdate = Convert.ToDateTime(ShiftDate);
            switch (shiftId)
            {
                case 1:
                    expectedOutTime = Convert.ToDateTime(string.Format("{0} {1}", shiftdate.ToShortDateString(), "23:00:00"));
                    break;
                case 2:
                    expectedOutTime = Convert.ToDateTime(string.Format("{0} {1}", shiftdate.ToShortDateString(), "14:00:00"));
                    break;
                case 3:
                    expectedOutTime = Convert.ToDateTime(string.Format("{0} {1}", shiftdate.ToShortDateString(), "20:30:00"));
                    break;
                case 4:
                    expectedOutTime = Convert.ToDateTime(string.Format("{0} {1}", shiftdate.ToShortDateString(), "18:00:00"));
                    break;
                case 5:
                    expectedOutTime = Convert.ToDateTime(string.Format("{0} {1}", shiftdate.ToShortDateString(), "06:00:00"));
                    break;
            }
            if (swipeOut < expectedOutTime)
            {
                earlyby = Convert.ToString(expectedOutTime - swipeOut);
            }
            else
            {
                earlyby = "00:00";
            }
            return earlyby;
        }

    }
}